func threeSumClosest(nums []int, target int) int {
    ans := math.MaxInt
    sort.Slice(nums, func (i, j int) bool {
        return nums[i] < nums[j]
    })
    for i:=0; i<len(nums)-2; i++ {
        if i>0 && nums[i] == nums[i-1]{
            continue
        }

        l := i+1
        r := len(nums)-1
        for l < r {
            sum := nums[i] + nums[l] + nums[r]

            if sum == target {
                return sum
            }

            if math.Abs(float64(target-sum)) < math.Abs(float64(target-ans)) {
                ans = sum
            }

            if sum < target {
                if l < r && nums[l] == nums[l+1]{
                    l++
                }
                l++
            }
            if sum > target {
                if l<r && nums[r] == nums[r-1]{
                    r--
                }
                r--
            }
        }
    }
    return ans
}